<template>
  <div class="myapp w-full h-full">
    <div class="main flex flex-row">
      <Sidebar class="sidebar-container ml-auto" />
      <div class="wrap h-full w-full">
        <div class="hd flex flex-row h-11 w-full items-center">
          <Hamburger :is-active="sidebar.opened" class="hamburger h-1/2" @toggle-click="toggleSidebar" />
          <Breadcrumb class="h-1/2 breadcrumb" />
        </div>
        <div class="mainSection">
          <!-- 列表 -->
          <div>
            <vxe-toolbar>
              <template #buttons>
                <vxe-button icon="vxe-icon-square-plus" @click="insertEvent()">新增</vxe-button>
              </template>
            </vxe-toolbar>

            <vxe-table class="!w-[99%]" border show-overflow ref="xTable" height="300"
              :column-config="{ resizable: true }" :row-config="{ isHover: true }" :data="tableData"
              @cell-dblclick="cellDBLClickEvent">
              <vxe-column type="seq" width="60"></vxe-column>
              <vxe-column field="username" title="用户名"></vxe-column>
              <vxe-column field="createTime" title="创建日期" :formatter="formatterDate"></vxe-column>
              <vxe-column field="loginDate" title="上次登陆时间" :formatter="formatterDate"></vxe-column>
              <!-- <vxe-column field="address" title="Address" show-overflow></vxe-column> -->
              <vxe-column title="操作" width="100" show-overflow>
                <template #default="{ row }">
                  <vxe-button type="text" icon="vxe-icon-edit" @click="editEvent(row)"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" @click="removeEvent(row)"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager
              :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
              v-model:current-page="tablePage.currentPage" v-model:page-size="tablePage.pageSize"
              :total="tablePage.total" @page-change="handlePageChange">
            </vxe-pager>
            <vxe-modal v-model="showEdit" @close="clearFormData" :title="selectRow ? '编辑&保存' : '新增&保存'" width="800"
              min-width="600" min-height="300" :loading="submitLoading" resize destroy-on-close>
              <template #default>
                <vxe-form :data="formData" :rules="formRules" title-align="right" title-width="100"
                  @submit="submitEvent">
                  <vxe-form-item title="新增用户" title-align="left" :title-width="200" :span="24"
                    :title-prefix="{ icon: 'vxe-icon-comment' }"></vxe-form-item>
                  <vxe-form-item field="username" title="用户名" :span="12" :item-render="{}">
                    <template #default="{ data }">
                      <vxe-input v-model="data.username" placeholder="请输入用户名"></vxe-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item field="password" title="密码" :span="12" :item-render="{}">
                    <template #default="{ data }">
                      <vxe-input v-model="data.password" type="password" placeholder="请输入密码"></vxe-input>
                    </template>
                  </vxe-form-item>

                  <!-- <vxe-form-item field="flag1" title="是否单身" :span="12" :item-render="{}">
                    <template #default="{ data }">
                      <vxe-radio-group v-model="data.flag1">
                        <vxe-radio label="Y" content="是"></vxe-radio>
                        <vxe-radio label="N" content="否"></vxe-radio>
                      </vxe-radio-group>
                    </template>
                  </vxe-form-item> -->
                  <vxe-form-item align="center" title-align="left" :span="24">
                    <template #default>
                      <vxe-button type="submit">提交</vxe-button>
                      <vxe-button type="reset" @click="clearFormData">重置</vxe-button>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-modal>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { storeToRefs } from "pinia"
import { useAppStore } from "@/store/modules/app"
import { Sidebar, Breadcrumb, Hamburger } from "@/layouts/components"
import { VXETable, VxeTableInstance, VxeColumnPropTypes, VxeFormPropTypes, VxeFormItemPropTypes, VxeTableEvents } from 'vxe-table'
import dayjs from "dayjs";
import { fromPairs } from "lodash-es";
import { ElMessage } from "element-plus";

const appStore = useAppStore()
const { sidebar } = storeToRefs(appStore)

/** 切换侧边栏 */
const toggleSidebar = () => {
  appStore.toggleSidebar(false)
}
interface RowVO {
  id: number
  name: string
  nickname: string
  role: string
  sex: string
  sex2: string[]
  num: number
  num1: number
  age: number
  flag1: boolean
  address: string
  date12: string
  date13: string
  date3: string
  checkedList: any[]
}
let { proxy } = getCurrentInstance() as any
let tablePage = ref({
  currentPage: 1,
  pageSize: 10,
  total: 10
})
const xTable = ref<VxeTableInstance<RowVO>>()

const formData = reactive({
  password: '',
  username: '',
})

const submitLoading = ref(false)
const showEdit = ref(false)
const selectRow = ref<RowVO | null>()
const tableData = ref<RowVO[]>([])

const sexList = ref([
  { label: '女', value: '0' },
  { label: '男', value: '1' }
])

const formRules = reactive<VxeFormPropTypes.Rules>({
  password: [
    { required: true, message: '请输入密码' },
    { min: 4, max: 21, message: '长度在 8 到 16 个字符' }
  ],
  username: [
    { required: true, message: '请输入用户名' },
    { min: 4, max: 21, message: '长度在 4 到 30 个字符' }
  ],

})

const clearFormData = () => {
  // showEdit.value = false;
  formData.username = '';
  formData.password = '';
}

const formatterDate: VxeColumnPropTypes.Formatter<RowVO> = ({ cellValue }) => {
  if (cellValue) {
    return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
  } else {
    return ''
  }
}

const visibleMethod: VxeFormItemPropTypes.VisibleMethod = ({ data }) => {
  return data.flag1 === 'Y'
}

const insertEvent = () => {
  Object.assign(formData, {
    name: '',
    nickname: '',
    role: '',
    sex: '',
    age: 0,
    num: 0,
    checkedList: [],
    flag1: false,
    date3: '',
    address: ''
  })
  selectRow.value = null
  showEdit.value = true
}

const editEvent = (row: RowVO) => {
  Object.assign(formData, row)
  selectRow.value = row
  showEdit.value = true
}

const cellDBLClickEvent: VxeTableEvents.CellDblclick<RowVO> = ({ row }) => {
  editEvent(row)
}

const removeEvent = async (row: RowVO) => {
  const type = await VXETable.modal.confirm('您确定要删除该数据?')
  if (type === 'confirm') {
    const $table = xTable.value
    if ($table) {
      $table.remove(row)
      let id = row.id
      let url = '/admin-api/system/user/delete'
      let params = {
        id
      }
      proxy.$http.delete(url, { params, Authorization: 'Bearer test1' }).then((v) => {
        if (v.data.data == true) {
          ElMessage.success('删除用户成功！')
          window.location.reload()
        }
      })
    }
  }
}

const submitEvent = () => {
  submitLoading.value = true
  setTimeout(() => {
    const $table = xTable.value
    if ($table) {
      submitLoading.value = false
      showEdit.value = false
      if (selectRow.value) {
        VXETable.modal.message({ content: '保存成功', status: 'success' })
        Object.assign(selectRow.value, formData)
      } else {
        let url = '/admin-api/system/user/create'
        let params = {
          username: formData.username,
          password: formData.password,
          nickname: formData.username
        }
        proxy.$http.post(url, params, { headers: { Authorization: 'Bearer test1' } }).then(v => {
          if (v.data.code == 0) {
            ElMessage.success('用户添加成功！');
            window.location.reload()
          }
        })
      }
    }
  }, 500)
}

onMounted(() => {
  /* 查询所有用户, 目前是只有管理员账号 */
  let url = '/admin-api/system/user/page';
  let params = {}
  proxy.$http.get(url, { params, Authorization: 'Bearer test1' }).then(v => {
    if (v.data.code == 0) {
      tableData.value = v.data.data.list
    } else {

    }
  }).catch((e) => {

  })
})

</script>

<style lang="scss" scoped>
$transition-time: 0.35s;

.main {
  width: 100%;
  height: 100%;
}

.wrap {
  .hd {
    width: 100%;

    .sidebar-container {
      transition: width $transition-time;
      width: var(--v3-sidebar-width) !important;
      height: 100%;
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      z-index: 1001;
      overflow: hidden;
    }

    .hamburger {
      display: flex;
      align-items: center;
      cursor: pointer;
    }

    .breadcrumb {
      float: left;
      line-height: 1.45rem !important;

      @media screen and (max-width: 576px) {
        display: none;
      }
    }
  }

  .mainSection {
    @apply w-full;
    height: calc(100% - 2.75rem);
  }

  .forCenter {
    justify-content: center;
    align-items: center;
  }

  :deep(.vxe-form .vxe-form--wrapper) {
    justify-content: center;
    align-items: center;
    margin: 55px;
  }
}
</style>
